package server

import (
	"fmt"
	"gitee.com/snxamdf/wui/config"
	"gitee.com/snxamdf/wui/logs"
	"gitee.com/snxamdf/wui/util"
	"net/http"
	"time"
)

type cookie struct {
	w http.ResponseWriter
	r *http.Request
}

//获得sessionID,如果不存在则创建一个
func getSessionId(w http.ResponseWriter, r *http.Request) string {
	sid := r.Header.Get(sessionId)
	if sid == "" {
		sid, _ = getCookie(r, sessionId)
	}
	if sid == "" {
		sid = util.MD5(fmt.Sprintf("%s-%d", sessionId, time.Now().Nanosecond()))
		//sid = fmt.Sprintf("%s:%s", sessionId, sid)
		setCookie(w, sessionId, sid)
		r.Header.Set(sessionId, sid)
	}
	return sid
}

func getCookie(r *http.Request, key string) (string, error) {
	if c, err := r.Cookie(key); err != nil {
		return "", err
	} else {
		return c.Value, nil
	}
}

func setCookie(w http.ResponseWriter, key, value string) {
	cookie := &http.Cookie{
		Name:     key,
		Value:    value,
		Path:     "/",
		Domain:   config.GetConfig("domain"),
		MaxAge:   config.GetConfigInt("sessionTimeout"),
		HttpOnly: true,
	}
	http.SetCookie(w, cookie)
}

func (m *cookie) Set(key string, value string) {
	setCookie(m.w, key, value)
}

func (m *cookie) Get(key string) string {
	r, err := getCookie(m.r, key)
	if err != nil {
		logs.Error("获取Cookie值错误：", err)
		return ""
	}
	return r
}
